package com.weibo.survey.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.weibo.survey.domain.User;
import com.weibo.survey.service.UserService;
import com.weibo.survey.utils.DataUtils;

@Controller
@Scope("prototype")
public class LoginAction extends BaseAction<User> implements SessionAware {
	private static final long serialVersionUID = 1L;
	private static final String LOGIN = "login";
	@Resource(name = "userService")
	private UserService userService;

	private Map<String, Object> session;

	@SkipValidation
	public String toLogin() {
		return LOGIN;
	}
	
	@SkipValidation
	public String logout() {
		session.remove("user");
		return LOGIN;
	}

	public String login() {
		model.setPassword(DataUtils.md5(model.getPassword()));
		User user = userService.login(model);
		if (user != null) {
			session.put("user", user);
			return SUCCESS;
		} else {
			// 放到栈顶
			ActionContext.getContext().getValueStack().set("msg", "用户名/密码错误");
			return INPUT;
		}
	}

	@Override
	public void validate() {
		if (StringUtils.isBlank(model.getEmail())) {
			addFieldError("email", "邮箱不能为空");
		}
		if (StringUtils.isBlank(model.getPassword())) {
			addFieldError("password", "密码不能为空");
		}
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
